<?php

namespace app\api\controller;

use think\Controller;
use app\api\model\Keep as Mkeep;

class Keep extends Basic
{
    /**
     * @PROJECT_NAME yydr
     * Notes: 收藏/取消收藏
     * @return void
     */
    public function user_keep()
            {
                //文章的ID $a_id
                $pid=input('post.pid','');
                //类型 /1 文章
                $type=$this->request->post('type','');
                if (empty($pid)){
                    json_fail('缺少ID');
                }
                if (empty($type)){
                    json_fail('缺少类型');

                }
                //查询用户是否已经收藏过该文章
                $keep = new Mkeep();

                $res = $keep::withTrashed()->where([
                    'user_id' => UID,
                    'pid' => $pid,
                    'type'=>$type
                ])->find();
                if (!empty($res)) {
//            //已关收藏过 根据delete_time判断现在是否收藏

                    if (empty($res['delete_time'])) {
                        //软删除时间 为空 ,已收藏. 则取消收藏 ,, 如果已收藏则取消收藏 否则  重新收藏
                        $result = $keep::destroy(['user_id' => UID, "pid" => $pid,'type'=>$type]);

                        if (empty($result)) {
                            json_success('取消收藏失败');
                        }else {
                            json_success('取消收藏成功');
                        }
                    } else {
                        //如果未收藏 则重新收藏
                        $result = $keep::withTrashed()->where(["user_id" => UID, "pid" => $pid,'type'=>$type])->update(["delete_time" => null, 'pid' => $pid]);

                        if (empty($result)) {
                            json_fail('收藏失败');
                        }
                        json_success('收藏成功');

                    }
                } else {
                    //第一次收藏  添加新的数据
                    $result = $keep->data(['user_id' => UID, 'pid' => $pid,'type'=>$type])->save();
                    if (empty($result)) {
                        json_fail('收藏失败');
                    }
                    json_success('收藏成功');

                }
            }


}